<template>
  <q-page class="flex flex-center">
    <div class="login-form">
      <div class="title">
        <h2 v-if="!step1">键入您的用户名或电子邮箱地址。</h2>
        <h2 v-else>请输入你的密码（暂不支持授权登录）。</h2>
      </div>
      <div v-if="step1" style="margin-bottom: 20px">
        <h5 style="color: #4d4d4d; font-size: 13px !important">
          <strong><span>用户名</span></strong
          >: {{ username }}
        </h5>
      </div>
      <q-input
        v-if="!step1"
        filled
        dense
        id="username"
        v-model="username"
        ref="usernameInput"
        label="用户名或电子邮箱地址 *"
        autofocus="autofocus"
        lazy-rules
        @keyup.enter="CheckUsername"
        :rules="[
          (val) => (val && val.length > 0) || '用户名或电子邮箱地址是必填项。',
          (val) =>
            (val && val.length > 2) ||
            '用户名或电子邮箱地址必须超过 2 个字符。',
          (val) => errorMsg.length === 0 || errorMsg,
        ]"
      />
      <q-input
        v-if="step1"
        filled
        dense
        v-model="password"
        ref="passwordInput"
        :error-message="errorMsg"
        label="密码 *"
        :type="isPwd ? 'password' : 'text'"
        lazy-rules
        id="password"
        autofocus="autofocus"
        @keyup.enter="Login"
        :rules="[
          (val) => (val && val.length > 0) || '密码是必填项。',
          (val) => errorMsg.length === 0 || errorMsg,
        ]"
      >
        <template v-slot:append>
          <q-icon
            :name="isPwd ? 'visibility_off' : 'visibility'"
            class="cursor-pointer"
            @click="isPwd = !isPwd"
          />
        </template>
      </q-input>
      <div class="from-actions">
        <q-btn
          label="下一步"
          v-if="!step1"
          dense
          style="
            background-color: #367b88;
            color: #fff;
            padding-left: 10px;
            padding-right: 10px;
          "
          :disable="!toStep1"
          @click="CheckUsername"
        ></q-btn>

        <q-btn
          label="完成"
          v-if="step1"
          dense
          style="
            background-color: #367b88;
            color: #fff;
            padding-left: 10px;
            padding-right: 10px;
          "
          :disable="!toStep2"
          @click="Login"
        ></q-btn>
      </div>
    </div>

    <q-btn
      label="上一步"
      v-if="step1"
      flat
      class="absolute-top-left"
      style="color: #367b88"
      @click="step1 = false"
    ></q-btn>
  </q-page>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
import { api, session } from "src/boot/axios.js";
import notify from "src/utility/notify";

const router = useRouter();
const $q = useQuasar();
const username = ref("");
const password = ref("");
const isPwd = ref(true);
const toStep1 = ref(false);
const toStep2 = ref(false);
const step1 = ref(false);
const errorMsg = ref("");
const authUUid = ref(null);
const usernameInput = ref(null);
const passwordInput = ref(null);

watch(username, () => {
  toStep1.value = username.value.length > 2;
});
watch(password, () => {
  toStep2.value = password.value.length > 0;
});

const CheckUsername = async () => {
  $q.loading.show();

  try {
    const res = (await api.get(`/user/login/${username.value}/verify`)).data;
    if (res.is_exists) {
      step1.value = true;
      authUUid.value = res.auth_uuid;
    } else {
      errorMsg.value = res.message;
    }
  } catch (ex) {
    if (ex.response !== undefined && ex.response.data.message) {
      notify.warn(ex.response.data.message);
    } else {
      notify.error(`用户名验证失败: ` + ex.message);
      console.error(ex);
    }
  } finally {
    usernameInput.value.validate();
    $q.loading.hide();
  }
};

const Login = async () => {
  $q.loading.show();

  try {
    const res = (
      await api.post(`/user/login/${authUUid.value}/pwd`, {
        pwd: password.value,
      })
    ).data;
    notify.success(res.message);
    var accessToken = res.access_token;
    await session.set("token", accessToken);
    setTimeout(() => {
      location.reload();
      $q.loading.hide();
    }, 2000);
  } catch (ex) {
    if (ex.response !== undefined && ex.response.data.message) {
      errorMsg.value = ex.response.data.message;
    } else {
      notify.error(`密码验证失败: ` + ex.message);
      console.error(ex);
    }
    passwordInput.value.validate();
    $q.loading.hide();
  }
};

const userInfo = ref(null);
onMounted(async () => {
  $q.loading.show();

  userInfo.value = await session.get("userInfo");
  if (userInfo.value !== null) {
    router.push("/chatgpt");
  }
  $q.loading.hide();
});
</script>

<style>
.error-message {
  font-size: 12px; /* 设置字体大小较小 */
  color: #ff0000; /* 设置字体颜色为红色 */
}

.login-form {
  max-width: 500px;
  flex: 1;
  text-align: center;
  padding-top: 20px;
}

.login-form > .title {
  margin-bottom: 30px;
}

.login-form > .title > h2 {
  font-size: 22px;
  line-height: 22px;
}

.from-actions {
  margin-top: 10px;
  margin-bottom: 30px;
}

.from-actions > .login-btn {
  box-shadow: none;
  background-color: #367b88;
  border: 0 none;
  color: #fff;
}

.login-option-link {
  color: #367b88;
  display: inline-block;
  margin-bottom: 15px;
  cursor: pointer;
}

.login-option-link:hover {
  color: #125f6e;
  background-color: rgba(237, 235, 233, 0.209);
}
</style>
